<?php

namespace App\Manage;


use App\Models\User;


class UserManage extends Manage
{


    // 父级
    // 添加，修改，删除，列表，停用 操作
    // TODO 操作日志

    // 列表
    // 返回列表数据
    public function lists($myUser, $options = [])
    {
        $opt      = $this->option();
        $keyword  = $opt->getData('keyword', null, 'trim');
        $page     = $opt->getData('page', 1, 'intval');
        $rows     = $opt->getData('rows', 15, 'intval');
        $is_edit  = $opt->getData('is_edit', null, 'intval');
        $from_uid = $opt->getData('from_uid', 0, 'intval');
        $mobile   = $opt->getData('mobile', null, 'trim');
        $email    = $opt->getData('email', null, 'trim');


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 条件
        $map   = [];
        $where = [['status', '>=', 0]];
        if($from_uid){
            $map['from_uid'] = $from_uid;
            $where[]         = ['from_uid', '=', $from_uid];
        }
        if(!is_null($is_edit)){
            $map['is_edit'] = $is_edit;
            $where[]        = ['is_edit', '=', $is_edit];
        }
        if($keyword){
            $map     = false;
            $where[] = $opt->orWhere('email|nickname|username|realname', 'like', $keyword);
        }
        if($mobile){
            $map     = false;
            $where[] = $opt->orWhere('mobile', 'like', "%$mobile%");
        }
        if($email){
            $map     = false;
            $where[] = $opt->orWhere('email', 'like', "%$email%");
        }


        // 模型 和 查询
        $model  = new User();
        $result = $model->listPageCache($map, $where, $page, $rows, "id DESC");
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 用户头像，粉丝数量，关注数量，金币数
        if($result['list']){
            foreach($result['list'] as $key => $item){
                // 整理
                //$result['list'][$key]['head_img'] = $this->getHeadImg($item['head_img']);
            }
        }

        return $result;
    }

    // 查找
    public function show($myUser, $options = [])
    {

        $opt = $this->option();
        $id  = $opt->getData('id', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $where = ['id' => $id];
        $model = new User();
        $info  = $model->oneFindCache($where, $where);
        if($info === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($info)){
            //return $this->_returnFail('你要查看的用户不存在！');
            return $this->_returnFail('user_has_no_exist');
        }

        // 整理
        $info = is_object($info) ? $info->toArray() : $info;
        unset($info['password']);
        // 整理
        $info['card_date_date'] = $info['card_date'] ? date('Y-m-d', $info['card_date']) : '';
        $info['card_date_show'] = $info['card_date'] ? date('m/y', $info['card_date']) : '';

        // 如果是build-admin
        $isBuild = $opt->getHeader('Build-Admin', 0, 'intval');
        if($isBuild){
            return ['row' => $info];
        }

        return $info;
    }

    // 启用禁用
    public function status($myUser, $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt    = $this->option();
        $id     = $opt->getData('id', 0, 'intval');
        $_value = $opt->getData('status', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }
        if(is_null($_value)){
            //return $this->_returnFail('是否启用状态必须填写！！');
            return $this->_returnFail('enable_disable_status_must_be_filled');
        }
        if(!in_array($_value, [0, 1, -1])){
            //return $this->_returnFail('是否启用状态必须为0或1！！');
            return $this->_returnFail('status_value_must_be_0_1');
        }

        // 执行
        $data   = ['status' => $_value];
        $model  = new User();
        $result = $model->oneEdit(['id' => $id], $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }


        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/

        return true;
    }

    // 改变（直接修改，软删除，改变状态，排序）
    public function edit($myUser, $options = [])
    {
        $opt = $this->option();
        $id  = $opt->getData('id', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 数据
        $data = $this->_before_edit();
        if($data === false){
            return false;
        }


        // 组合数据
        $model = new User();
        $data  = $model->filterField($data, true);
        if($data === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($data)){
            //return $this->_returnFail('不能修改为空！');
            return $this->_returnFail('send_data_to_be_modify');
        }


        // 验证
        $where = ['id' => $id];
        $data  = $model->checkData($data, $where);
        if($data === false){
            return false;
        }


        // 检查唯一性
        $data = $model->checkUser($data, $where);  // 用户名是否重复
        if($data === false){
            return $this->_returnFail($model->getError());
        }


        // 执行
        $where  = $this->editWhere();
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }


        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/

        return true;
    }

    // 树状
    public function add($myUser, $options = [])
    {
        // 数据
        $data = $this->_before_add();
        if($data === false){
            return false;
        }


        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        // 组合数据
        $model = new User();
        $data  = $model->filterField($data, true);
        if($data === false){
            return $this->_returnFail($model->getError());
        }
        if(empty($data)){
            //return $this->_returnFail('请填写添加的数据！');
            return $this->_returnFail('add_the_saved_data');
        }

        // 验证
        $data = $model->checkData($data);
        if($data === false){
            return false;
        }

        // 唯一性
        $data = $model->checkUser($data);
        if($data === false){
            return false;
        }

        // 保存
        $result = $model->oneAdd($data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/

        return true;
    }


    // 修改密码
    public function password($myUser, $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt      = $this->option();
        $password = $opt->getData('password', '123456', 'trim');
        $id       = $opt->getData('id', 0, 'intval');
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }

        $data  = ['password' => $password,];
        $where = ['id' => $id];
        $model = new User();
        $data  = $model->checkData($data, $where);
        if($data === false){
            return $this->_returnFail($model->getError());
        }

        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/


        return true;
    }


    // 删除（软删除）
    public function softDel($field = 'status', $myUser = [], $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt = $this->option();
        $id  = $opt->getData('id', 0, 'intval');
        $ids = $opt->getData('ids', [], 'is_array');
        // 修改记录
        if(empty($id) && empty($ids)){
            //return $this->_returnFail('请指定删除记录！');
            return $this->_returnFail('select_operation_id');
        }

        // 条件
        $where = [];
        if($id){
            $where[] = ['id', '=', $id];
        }
        if($ids){
            $where[] = [
                function($qq) use ($ids) {
                    $qq = $qq->whereIn('id', $ids);
                },
            ];
        }


        // 查询
        $model = new User();
        $lists = $model->where($where)->get()->toArray();;  //->recycle()
        if(empty($lists)){
            //return $this->_returnFail('你要删除的数据不存在！！');
            return $this->_returnFail('data_delete_has_not_exist');
        }

        // 缓存操作
        $model->deleteCacheList($lists);

        // 删除
        $res = $model->where($where)->update([$field => -1]);

        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/

        return true;
    }


    // 添加
    protected function _before_add()
    {
        $opt    = $this->option();
        $mobile = $opt->getData('mobile', '', 'trim');
        $email  = $opt->getData("email", null, "trim");
        /*if(empty($mobile)){
            //return $this->_returnFail('请填写手机号码！');
            return $this->_returnFail('enter_your_mobile_number');
        }*/

        /*$isMobile = preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $mobile);
        if(!$isMobile){
            //return $this->_returnFail('请填写正确手机号！');
            return $this->_returnFail('enter_the_correct_phone_number');
        }*/


        // 检查手机号是否存在
        $userDb = new User();
        $where  = [['mobile', '=', $mobile], ['status', '<>', -1]];
        $info   = $userDb->where($where)->first();
        if($info){
            //return $this->_returnFail('该手机号已经存在！');
            return $this->_returnFail('mobile_has_exist');
        }

        // 组合
        $data = [
            //'id'        => $opt->getData("id", null, "intval"),
            //'username'  => $opt->getData("username", null, "trim"),
            //'phone'     => $opt->getData("phone", null, "trim"),
            'password'    => $opt->getData("password", null, "trim"),
            'head_img'    => $opt->getData("head_img", null, "trim"),
            'mobile'      => $mobile,
            'email'       => $email,
            'sex'         => $opt->getData("sex", null, "intval"),
            'city'        => $opt->getData("city", null, "trim"),
            'reg_ip'      => $opt->getData("reg_ip", null, "trim"),
            'reg_time'    => $opt->getData("reg_time", null, "intval"),
            'last_ip'     => $opt->getData("last_ip", null, "trim"),
            'last_time'   => $opt->getData("last_time", null, "intval"),
            'sign'        => $opt->getData("sign", null, "trim"),
            'status'      => $opt->getData("status", 0, "intval"),
            'from_uid'    => $opt->getData("from_uid", null, "intval"),
            'card_name'   => $opt->getData("card_name", null, "trim"),
            'card_number' => $opt->getData("card_number", null, "trim"),
            //'card_date'   => $opt->getData("card_date", null, "intval"),
            'mtime'       => $opt->getData("mtime", null, "intval"),
        ];


        // 审核内容
        // $this->baiduTextCensor($data);
        // 设置 head_img
        if($data['head_img']){
            $model = new User();
            // 设置
            $data['head_img'] = $model->setPicAttribute($data['head_img']);
        }


        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        // 参数
        $opt    = $this->option();
        $id     = $opt->getData('id', 0, 'intval');
        $mobile = $opt->getData('mobile', '', 'trim');
        $email  = $opt->getData("email", null, "trim");
        if(empty($id)){
            //return $this->_returnFail('请指定查看记录！');
            return $this->_returnFail('select_operation_id');
        }
        /*if(empty($mobile)){
            //return $this->_returnFail('请填写手机号码！');
            return $this->_returnFail('enter_your_mobile_number');
        }*/

        /*$isMobile = preg_match("/^1[3|4|5|6|7|8|9][0-9]\d{8}$/", $mobile);
        if(!$isMobile){
            //return $this->_returnFail('请填写正确手机号！');
            return $this->_returnFail('enter_the_correct_phone_number');
        }*/


        // 检查手机号是否存在
        $userDb = new User();
        $where  = [['mobile', '=', $mobile], ['status', '<>', -1], ['id', '<>', $id]];
        $info   = $userDb->where($where)->first();
        if($info){
            //return $this->_returnFail('该手机号已经存在！');
            return $this->_returnFail('mobile_has_exist');
        }

        // 组合
        $data = [
            //'id'        => $opt->getData("id", null, "intval"),
            //'username'  => $opt->getData("username", null, "trim"),
            //'phone'     => $opt->getData("phone", null, "trim"),
            'password'    => $opt->getData("password", null, "trim"),
            'head_img'    => $opt->getData("head_img", null, "trim"),
            'mobile'      => $mobile,
            'email'       => $email,
            'sex'         => $opt->getData("sex", null, "intval"),
            'city'        => $opt->getData("city", null, "trim"),
            'reg_ip'      => $opt->getData("reg_ip", null, "trim"),
            'reg_time'    => $opt->getData("reg_time", null, "intval"),
            'last_ip'     => $opt->getData("last_ip", null, "trim"),
            'last_time'   => $opt->getData("last_time", null, "intval"),
            'sign'        => $opt->getData("sign", null, "trim"),
            'status'      => $opt->getData("status", 1, "intval"),
            'from_uid'    => $opt->getData("from_uid", null, "intval"),
            'card_name'   => $opt->getData("card_name", null, "trim"),
            'card_number' => $opt->getData("card_number", null, "trim"),
            //'card_date'   => $opt->getData("card_date", null, "intval"),
            'ctime'       => $opt->getData("ctime", null, "intval"),
            'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        // 审核内容
        //$this->baiduTextCensor($data);
        // 设置 head_img
        if($data['head_img']){
            $model = new User();
            // 设置
            $data['head_img'] = $model->setPicAttribute($data['head_img']);
        }

        return $data;
    }

}


